<template>
  <div class="edit-page-wrap edit-page-wrap-1">
    <Head title="方案信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="130px"
          class="edit-form-wrap"
        >
          <el-form-item label="方案名称" prop="planName">
            <el-input
              v-model.trim="ruleForm.planName"
              placeholder="请输入方案名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="流量方" prop="orgId">
            <div v-if="id">{{ data.orgName }}</div>
            <qc-select
              v-else
              :value="ruleForm.orgId"
              :remote="true"
              :filterable="true"
              :options="optionsS.orgData"
              placeholder="请输入搜索关键词"
              @change="handleChangeOrg"
            >
            </qc-select>
          </el-form-item>
          <el-form-item label="生效时间" prop="times">
            <div class="edit-date-wrap" v-if="id">
              {{ ruleForm.times[0] }} 至 {{ ruleForm.times[1] }}
            </div>
            <div class="edit-date-wrap" v-else>
              <el-date-picker
                v-model="ruleForm.times"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="电站价格信息">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="130px"
          class="edit-form-wrap"
        >
          <el-form-item label="价格设置（商务价）" prop="chargeDiscount">
            <div v-if="id">电费折扣: {{ ruleForm.chargeDiscount }}%</div>
            <div v-else>
              <span class="money-title">电费折扣（%）:</span>
              <el-input
                v-model.trim="ruleForm.chargeDiscount"
                placeholder="请输入电费折扣"
                maxlength="3"
                style="width: 190px"
                clearable
              />
            </div>
          </el-form-item>
          <el-form-item label="" prop="serviceDiscount" class="has-tips">
            <div v-if="id">服务费折扣: {{ ruleForm.serviceDiscount }}%</div>
            <div v-else>
              <span class="money-title">服务费折扣（%）:</span>
              <el-input
                v-model.trim="ruleForm.serviceDiscount"
                placeholder="请输入服务费折扣"
                maxlength="3"
                style="width: 190px"
                clearable
              />

              <div class="tip">
                <div class="icon"></div>
                折扣价格设置，即在电站基础价格上打折后推送给流量方，打折后的价格仅保留4位小数，其他舍弃。示例：电站基础价格为1.1291元/度，折扣为80%，计算后价格为0.90328元/度，推送给流量方的价格为0.9032元/度。
                注：互联互通电站的基础价为入口方案折扣后的价格。
              </div>
            </div>
          </el-form-item>
          <el-form-item
            label="站点推送价格"
            prop="stationPriceType"
            class="has-tips"
          >
            <el-radio-group
              v-model="ruleForm.stationPriceType"
              v-for="(item, index) in optionsS.stationPriceTypeData"
              :key="index"
              @change="changeCompanyType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              原价：电站所设置的原始价格；商务价：在电站原始价格基础上进行了电费、服务费折扣后的价格
            </div>
          </el-form-item>
          <el-form-item label="结算推送价格" prop="settlePriceType">
            <el-radio-group
              v-model="ruleForm.settlePriceType"
              v-for="(item, index) in optionsS.settlePriceTypeData"
              :key="index"
              @change="changeCompanyType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="开放电站">
      <template #content>
        <el-form
          ref="ruleFormRef2"
          :model="ruleForm"
          :rules="rules"
          label-width="130px"
          class="edit-form-wrap"
        >
          <el-form-item label="提供方" prop="openStationType">
            <el-checkbox-group
              v-model="ruleForm.openStationType"
              @change="handleOpenStation"
            >
              <el-checkbox
                v-for="item in optionsS.openStationTypeData"
                :key="item.value"
                :label="item.label"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="选择运营商" prop="orgIds">
            <QcTree
              ref="treeOrgRef"
              :setCheckedKeys="ruleForm.orgIds"
              :data="optionsS.orgTree"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckOrg"
            ></QcTree>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" v-btnAntiShake="getStations"
              >确认</el-button
            >
            <span class="sure-tips"> 点击“确认”后再进行站点选择!</span>
          </el-form-item>
          <el-form-item label="选择电站" prop="stationIds">
            <QcTree
              ref="treeStationRef"
              :setCheckedKeys="ruleForm.stationIds"
              :data="optionsS.stationTree"
              :showCheckbox="true"
              @handleCheck="handleStationId"
            ></QcTree>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>
  
  <script lang="ts" setup>
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import { savePlan, updatePlan, getPlan } from '@/service/apis/docking';
import {
  queryCarList,
  areaStationTreeDataByOrgId,
  queryAllFlow,
} from '@/service/apis/org';
import { queryDicByParent } from '@/service/apis/api';
import { IS_DECIMAL_2, IS_INT_0 } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;
const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const ruleFormRef2 = ref<FormInstance>();

const data = reactive({
  type: {},
  orgName: '',
});

const optionsS = reactive({
  orgData: [] as any,
  orgTree: [] as any,
  stationTree: [] as any,
  stationPriceTypeData: [] as any,
  settlePriceTypeData: [] as any,
  openStationTypeData: [] as any,
});

const disabledDate = (time: any) => {
  return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
};
const checkTime = (rule: any, value: any, callback: any) => {
  const endData = `${value[1]} 23:59:59`;
  if (new Date(endData).getTime() < new Date().getTime()) {
    callback(new Error('结束时间不能小于当前时间'));
  }
  callback();
};

let ruleForm: any = reactive({
  id: id,
  secondaryPricingType: '0',
  orgId: [] as any,
  planName: '',
  chargeDiscount: 100,
  serviceDiscount: 100,
  stationPriceType: '',
  settlePriceType: '0',
  openStationType: ['平台直连'],
  orgIds: [] as any,
  stationIds: [] as any,
  times: [] as any,
});
const checkTreeOrg = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeOrgRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的电站运营商'));
  }
  callback();
};
const rules = reactive<FormRules>({
  planName: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
  orgId: [{ required: true, message: '请选择流量方', trigger: 'change' }],
  times: [
    {
      required: true,
      message: '请选择生效时间',
      trigger: ['blur', 'change'],
    },
    { validator: checkTime, trigger: ['blur', 'change'] },
  ],
  chargeDiscount: [
    { required: true, message: '请输入电费折扣', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '请输入大于等于0的正整数',
      trigger: 'blur',
    },
  ],
  serviceDiscount: [
    { required: true, message: '请输入服务费折扣', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '请输入大于等于0的正整数',
      trigger: 'blur',
    },
  ],

  stationPriceType: [
    { required: true, message: '请选择站点推送价格', trigger: 'change' },
  ],
  settlePriceType: [
    { required: true, message: '请选择结算推送价格', trigger: 'change' },
  ],
  openStationType: [
    { required: true, message: '请选择提供方', trigger: 'change' },
  ],
  orgIds: [
    { required: true, message: '请选择运营商', trigger: 'change' },
    { validator: checkTreeOrg, trigger: ['blur', 'change'] },
  ],
  stationIds: [{ required: true, message: '请选择电站', trigger: 'change' }],
});

const back = () => {
  router.go(-1);
};

queryDicByParent({
  listDtos: ['planPriceType', 'planOpenStationType'],
}).then((res: any) => {
  optionsS.stationPriceTypeData = res.planPriceType;
  optionsS.settlePriceTypeData = res.planPriceType;
  optionsS.openStationTypeData = res.planOpenStationType;
});

// 更改企业类型
const changeCompanyType = (e: any) => {
  console.log(e);
  ruleForm.type = e;
  getOrgs();
};

const handleChangeOrg = async (e: any) => {
  ruleForm.orgId = e;
};

// 获取流量方
queryAllFlow({
  type: '5',
}).then((res: any) => {
  if (res) {
    optionsS.orgData = res.listMap;
  }
});
let treeOrgRef = ref();
let treeStationRef = ref();
// 提供方选择
const handleOpenStation = (e: any) => {
  if (e.includes('平台直连')) {
    if (e.length == 2) {
      ruleForm.openStationType = [0, 1];
      ruleForm.openStationType1 = [0, 1];
      data.type = {
        type: 0,
      };
    } else {
      ruleForm.openStationType = [0];
      ruleForm.openStationType1 = [0];
      data.type = {
        attr: 5,
      };
    }
  } else if (e.includes('互联互通')) {
    if (e.length == 2) {
      ruleForm.openStationType = [0, 1];
      ruleForm.openStationType1 = [0, 1];
      data.type = {
        type: 0,
      };
    } else {
      ruleForm.openStationType = [1];
      ruleForm.openStationType1 = [1];
      data.type = {
        attr: 3,
      };
    }
  } else {
    ruleForm.openStationType = [];
    ruleForm.openStationType1 = [];
    data.type = {};
  }
  ruleForm.openStationType = e;
  ruleForm.orgIds = [];
  optionsS.orgTree = [];
  ruleForm.stationIds = [];
  optionsS.stationTree = [];
  if (e.length > 0) {
    getOrgs();
  }
  nextTick(() => {
    treeOrgRef.value.setCheckedKeys([]);
    treeStationRef.value.setCheckedKeys([]);
  });

  console.log(ruleForm.openStationType);
  console.log(ruleForm.orgIds);
  console.log(ruleForm.stationIds);
};

// 获取运营商
const getOrgs = () => {
  queryCarList(data.type).then((res: any) => {
    if (res) {
      optionsS.orgTree = res;
    }
  });
};

handleOpenStation(ruleForm.openStationType);

const handleCheckOrg = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.orgIds = checkedChildData;
  optionsS.stationTree = [];
  ruleFormRef2.value?.validateField('orgIds');
};

const handleStationId = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.stationIds = checkedChildData;
  ruleFormRef2.value?.validateField('stationIds');
};
// 获取运营商
const getStationsData = (arr: any) => {
  areaStationTreeDataByOrgId({ operatorIds: arr }).then((res: any) => {
    if (res) {
      optionsS.stationTree = res;
      if (id) {
        const timer = setTimeout(() => {
          treeStationRef.value?.setCheckedKeys(ruleForm.stationIds);
          const ids = treeStationRef.value?.getCheckedChildData();
          ruleForm.stationIds = ids;
          clearTimeout(timer);
        }, 500);
      }
    } else {
      optionsS.stationTree = [];
      if (id) {
        ruleForm.stationIds = [];
      }
    }
  });
};
const getStations = () => {
  ruleFormRef2.value?.validateField('orgIds', (valid: any) => {
    if (valid) {
      const arr: any = [];
      const treeOrg = treeOrgRef.value?.getCheckedNodes();
      treeOrg.forEach((item: any) => {
        if (item.type !== 'CHANNEL') {
          arr.push(item.id);
        }
      });
      getStationsData(arr);
    }
  });
  // if (ruleForm.orgIds.length < 1) {
  //   ElMessage({
  //     showClose: true,
  //     message: '请选择运营商',
  //     type: 'warning',
  //   });
  //   return;
  // }
  // areaStationTreeDataByOrgId({ operatorIds: ruleForm.orgIds }).then(
  //   (res: any) => {
  //     if (res) {
  //       optionsS.stationTree = res;
  //     }
  //   }
  // );
};
// 详情赋值
if (id) {
  getPlan({ id }).then((res: any) => {
    if (res) {
      for (const key in ruleForm) {
        if (res[key]) {
          ruleForm[key] = res[key];
        }
      }
      ruleForm.times = [res.startTime, res.endTime];
      data.orgName = res.orgName;
      const openStationType = ruleForm.openStationType.split(',');
      if (openStationType.length == 2) {
        ruleForm.openStationType = ['平台直连', '互联互通'];
        ruleForm.openStationType1 = [0, 1];
        data.type = {
          type: 0,
        };
      } else if (openStationType.length == 1) {
        if (ruleForm.openStationType[0] == 0) {
          ruleForm.openStationType = ['平台直连'];
          ruleForm.openStationType1 = [0];
          data.type = {
            attr: 5,
          };
        } else if (ruleForm.openStationType[0] == 1) {
          ruleForm.openStationType = ['互联互通'];
          ruleForm.openStationType1 = [1];
          data.type = {
            attr: 3,
          };
        }
      }
      getOrgs();
      getStationsData(ruleForm.orgIds);
    }
  });
} else {
  getOrgs();
}

// 提交
const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  console.log(ruleForm);
  if (!ruleFormRef.value || !ruleFormRef1.value || !ruleFormRef2.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef1.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef2.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormRef1.value.scrollToField(key);
        ruleFormRef2.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  const form = { ...ruleForm };
  form.startTime = ruleForm.times[0];
  form.endTime = ruleForm.times[1];
  form.openStationType = form.openStationType1.join(',');

  // 选择运营商
  const arr: any = [];
  const treeOrg = treeOrgRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  ruleForm.orgIds = arr;

  console.log('form====', form);
  if (id) {
    updatePlan(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    savePlan(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>
<style lang="scss">
.edit-page-wrap-1 {
  .edit-form-wrap {
    .el-input-number {
      .el-input {
        .el-input__wrapper {
          width: 0 !important;
        }
      }
    }
  }
}
.money-title {
  font-size: 12px;
  width: 97px;
  text-align: right;
  margin-right: 12px;
}
.sure-tips {
  color: var(--el-color-primary);
  margin-left: 12px;
}
</style>
